const db = require('../config/database');

class OrderController {
  // 获取订单列表
  async getOrders(req, res) {
    // 从JWT token中获取userId（通过中间件）
    const userId = req.user ? req.user.id : req.query.userId;
    const { status, page = 1, pageSize = 10 } = req.query;
    const offset = (page - 1) * pageSize;

    try {
      let sql = 'SELECT * FROM orders WHERE 1=1';
      const params = [];

      if (userId) {
        sql += ' AND user_id = ?';
        params.push(userId);
      } else {
        // 如果没有userId，返回空列表
        return res.json({
          success: true,
          data: {
            list: [],
            total: 0,
            page: parseInt(page),
            pageSize: parseInt(pageSize)
          }
        });
      }

      if (status !== undefined) {
        sql += ' AND status = ?';
        params.push(status);
      }

      sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
      params.push(parseInt(pageSize), offset);

      const [orders] = await db.query(sql, params);

      // 获取总数
      let countSql = 'SELECT COUNT(*) as total FROM orders WHERE user_id = ?';
      const countParams = [userId];

      if (status !== undefined) {
        countSql += ' AND status = ?';
        countParams.push(status);
      }

      const [countResult] = await db.query(countSql, countParams);

      res.json({
        success: true,
        data: {
          list: orders,
          total: countResult[0].total,
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        }
      });
    } catch (error) {
      console.error('获取订单列表错误:', error);
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 获取订单详情
  async getOrderDetail(req, res) {
    const { orderNo } = req.params;
    const userId = req.user ? req.user.id : null;

    try {
      let sql = 'SELECT * FROM orders WHERE order_no = ?';
      const params = [orderNo];

      // 如果用户已登录，只返回该用户的订单
      if (userId) {
        sql += ' AND user_id = ?';
        params.push(userId);
      }

      const [orders] = await db.query(sql, params);

      if (orders.length === 0) {
        return res.json({ success: false, message: '订单不存在' });
      }

      const order = orders[0];

      // 如果订单已支付但未发货，尝试自动发货
      if (order.status === 1 && (!order.delivery_status || order.delivery_status === 0) && order.product_id) {
        try {
          // 查询商品的网盘地址
          const [products] = await db.query(
            'SELECT download_url FROM products WHERE id = ?',
            [order.product_id]
          );

          if (products.length > 0 && products[0].download_url) {
            const downloadUrl = products[0].download_url;
            
            // 更新订单发货信息（自动发货）
            await db.query(
              'UPDATE orders SET delivery_content = ?, delivery_status = 1, delivery_time = NOW() WHERE order_no = ?',
              [downloadUrl, orderNo]
            );

            // 重新查询订单以获取最新发货信息
            const [updatedOrders] = await db.query(sql, params);
            if (updatedOrders.length > 0) {
              order = updatedOrders[0];
            }
          }
        } catch (error) {
          console.error('自动发货失败:', error);
          // 即使自动发货失败，也继续返回订单信息
        }
      }

      // 返回订单详情，包含发货信息
      res.json({
        success: true,
        data: {
          ...order,
          // 格式化发货信息
          deliveryInfo: order.delivery_status === 1 ? {
            status: '已发货',
            content: order.delivery_content,
            time: order.delivery_time
          } : {
            status: '待发货',
            content: null,
            time: null
          }
        }
      });
    } catch (error) {
      console.error('获取订单详情错误:', error);
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 取消订单
  async cancelOrder(req, res) {
    const { orderNo } = req.params;

    try {
      const [result] = await db.query(
        'UPDATE orders SET status = 2 WHERE order_no = ? AND status = 0',
        [orderNo]
      );

      if (result.affectedRows === 0) {
        return res.json({ success: false, message: '订单不存在或无法取消' });
      }

      res.json({ success: true, message: '订单已取消' });
    } catch (error) {
      console.error('取消订单错误:', error);
      res.json({ success: false, message: '系统错误' });
    }
  }

  // ========== 管理后台专用方法（无需认证）==========

  // 获取所有订单列表（管理后台）
  async getOrdersAdmin(req, res) {
    const { status, openid, page = 1, pageSize = 10 } = req.query;
    const offset = (page - 1) * pageSize;

    try {
      let sql = 'SELECT * FROM orders WHERE 1=1';
      const params = [];

      if (status !== undefined && status !== '') {
        sql += ' AND status = ?';
        params.push(status);
      }

      if (openid) {
        sql += ' AND openid LIKE ?';
        params.push(`%${openid}%`);
      }

      sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
      params.push(parseInt(pageSize), offset);

      const [orders] = await db.query(sql, params);

      // 获取总数
      let countSql = 'SELECT COUNT(*) as total FROM orders WHERE 1=1';
      const countParams = [];

      if (status !== undefined && status !== '') {
        countSql += ' AND status = ?';
        countParams.push(status);
      }

      if (openid) {
        countSql += ' AND openid LIKE ?';
        countParams.push(`%${openid}%`);
      }

      const [countResult] = await db.query(countSql, countParams);

      res.json({
        success: true,
        data: {
          list: orders,
          total: countResult[0].total,
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        }
      });
    } catch (error) {
      console.error('获取订单列表错误（管理后台）:', error);
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 获取订单详情（管理后台）
  async getOrderDetailAdmin(req, res) {
    const { orderNo } = req.params;

    try {
      const [orders] = await db.query('SELECT * FROM orders WHERE order_no = ?', [orderNo]);

      if (orders.length === 0) {
        return res.json({ success: false, message: '订单不存在' });
      }

      const order = orders[0];

      res.json({
        success: true,
        data: {
          ...order,
          deliveryInfo: order.delivery_status === 1 ? {
            status: '已发货',
            content: order.delivery_content,
            time: order.delivery_time
          } : {
            status: '待发货',
            content: null,
            time: null
          }
        }
      });
    } catch (error) {
      console.error('获取订单详情错误（管理后台）:', error);
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 查询支付结果（管理后台）
  async queryPaymentAdmin(req, res) {
    const { orderNo } = req.params;
    const payController = require('./payController');
    
    // 直接调用支付控制器的查询方法
    return payController.queryPayment({ params: { orderNo } }, res);
  }

  // 手动发货（管理后台）
  async deliverOrder(req, res) {
    const { orderNo } = req.params;
    const { delivery_content } = req.body;

    try {
      // 查询订单
      const [orders] = await db.query('SELECT * FROM orders WHERE order_no = ?', [orderNo]);

      if (orders.length === 0) {
        return res.json({ success: false, message: '订单不存在' });
      }

      const order = orders[0];

      // 检查订单状态
      if (order.status !== 1) {
        return res.json({ success: false, message: '订单未支付，无法发货' });
      }

      if (order.delivery_status === 1) {
        return res.json({ success: false, message: '订单已发货，请勿重复操作' });
      }

      // 确定发货内容
      let finalDeliveryContent = delivery_content;

      // 如果没有填写发货内容，使用商品的网盘地址
      if (!finalDeliveryContent || finalDeliveryContent.trim() === '') {
        const [products] = await db.query(
          'SELECT download_url FROM products WHERE id = ?',
          [order.product_id]
        );

        if (products.length > 0 && products[0].download_url) {
          finalDeliveryContent = products[0].download_url;
        } else {
          return res.json({ success: false, message: '未填写发货内容，且商品未配置网盘地址' });
        }
      }

      // 更新订单发货信息
      const [result] = await db.query(
        'UPDATE orders SET delivery_content = ?, delivery_status = 1, delivery_time = NOW() WHERE order_no = ?',
        [finalDeliveryContent, orderNo]
      );

      if (result.affectedRows === 0) {
        return res.json({ success: false, message: '发货失败' });
      }

      res.json({
        success: true,
        message: '发货成功',
        data: {
          delivery_content: finalDeliveryContent
        }
      });
    } catch (error) {
      console.error('发货失败:', error);
      res.json({ success: false, message: '系统错误' });
    }
  }
}

module.exports = new OrderController();


